package gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import nonGameLogic.MatchReplay;
import persistence.PersistenceLayer;

public class SelectReplayFrame extends JFrame {

	private static final long serialVersionUID = 92296568029613307L;

	private MatchReplay[] replays;
	private JList<String> replayList;
	
	public SelectReplayFrame() {
		
		JScrollPane mainScrollPanel = new JScrollPane();
		getContentPane().add(mainScrollPanel, BorderLayout.CENTER);
		
		replayList = new JList<String>();
		mainScrollPanel.setViewportView(replayList);
		
		JPanel southPanel = new JPanel();
		FlowLayout fl_southPanel = (FlowLayout) southPanel.getLayout();
		fl_southPanel.setVgap(20);
		fl_southPanel.setHgap(20);
		getContentPane().add(southPanel, BorderLayout.SOUTH);
		
		JPanel southContentPane = new JPanel();
		southPanel.add(southContentPane);
		southContentPane.setLayout(new BoxLayout(southContentPane, BoxLayout.X_AXIS));
		
		JButton Cancelar = new JButton("Cancelar");
		Cancelar.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				OnCancel();
			}
		});
		southContentPane.add(Cancelar);
		
		JButton Assistir = new JButton("Assistir...");
		Assistir.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				OnAssistirReplay();
			}
		});
		southContentPane.add(Assistir);
		
		replays = PersistenceLayer.getMatchProvider().ListMatches();
		fillList();
		
		this.pack();
		this.setVisible(true);
	}
	
	private void OnAssistirReplay() {
		(new WatchReplayFrame(replays[replayList.getSelectedIndex()])).setVisible(true);
	}
	private void OnCancel() {
		this.setVisible(false);
		this.dispose();
	}
	
	private void fillList() {
		DefaultListModel<String> model = new DefaultListModel<String>();
		
		for (int i = 0; i < replays.length; i++) {
			MatchReplay mr = replays[i];
			
			model.addElement(mr.getJogadorBranco().getName() + " vs " + mr.getJogadorPreto().getName());
		}
		
		replayList.setModel(model);
		replayList.setSelectedIndex(0);
	}
}
